var wxCharts = require('../../../utils/wxcharts.js');
var app = getApp();
var daylineChart = null;
var yuelineChart = null;

Page({
  data: {
    id: null,
    answerrecordid:null,
    survey: null,
    color: [
      "#ffbe26",
      "#fc5b23",
      "#198ded",
      "#3bc06b",
      "#c90ff0"
    ],
    style: "wu",
    columnsize:0,
    queslist: [],
    quesbarlist:[],
    chartlist: [],
    chartinfo:['','','','','','',''],
    server: app.api.server
  },
  onShareAppMessage: function() {
    var url = '/pages/show_questionnaire/show_questionnaire?id=' + this.data.id;
    console.log(url);

    var title = app.globalData.userInfo.nickName + "邀您填写" + "《" + this.data.survey.surveyname + "》"

    return {
      title: title,
      path: url,
    }
  },
  onLoad: function(e) {
    this.setData({
      id: e.id,
      answerrecordid: e.answerrecordid,
      columnsize:e.columnsize
    })
    wx.showNavigationBarLoading()
    var that = this;
    app.api.api_paper_chartdetail({
      surveyid: this.data.id,
      answerrecordid: this.data.answerrecordid,
    }).then(res => {
      console.log(res);
      that.setData({
        queslist: res.linechartlist,
        quesbarlist: res.barchartlist,
      });
      //todo
      that.getMothElectro();
      wx.hideNavigationBarLoading();
    });
  },
  createSimulationData: function(geti) {
    var that = this;
    var categories = [];
    var data = [];
    var desc = [];
    var name = "--";
    for (var i = 0; i < 10; i++) {
      categories.push('月' + (i + 1));
      data.push(Math.random() * 100 / 10 % 2);
    }
    for (var i in this.data.queslist) {
      if(i === geti+''){
      name = this.data.queslist[i].showname;
      categories = this.data.queslist[i].ques_categories;
      data = this.data.queslist[i].ques_data;
      desc = this.data.queslist[i].ques_desc;
      break;
      }
    }
    // data[4] = null;
    return {
      name: name,
      categories: categories,
      data: data,
      desc: desc
    }
  },
  updateData: function() {
    //再请求一次 todo 待测试
    var that = this;
    app.api.api_paper_chartdetail({
      surveyid: this.data.id,
      answerrecordid: this.data.answerrecordid,
    }).then(res => {
      console.log(res);
      that.setData({
        queslist: res
      });

      var simulationData = this.createSimulationData();
      var series = [{
        name: simulationData.name,
        data: simulationData.data,
        desc: simulationData.desc,
        format: function (val, name) {
          return val.toFixed(2) + '';
        }
      }];
      lineChart.updateData({
        categories: simulationData.categories,
        series: series
      });

    });
    
  },

  getMothElectro: function() {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    var addchartlist = [];
    for (var i = 0; i < this.data.columnsize ; i++) {
      var simulationData = this.createSimulationData(i);
      if (simulationData.data == null || simulationData.data.length === 0){
        continue;
      }
      var _yuelineChart = new wxCharts({ //当月用电折线图配置
        canvasId: 'yueEle'+i,
        type: 'line',
        categories: simulationData.categories,
        animation: true,
        // background: '#f5f5f5',
        series: [{
          name: simulationData.name,
          data: simulationData.data,
          desc: simulationData.desc,
          format: function(val, name) {
            return val.toFixed(0);
          }
        }],
        xAxis: {
          disableGrid: true
        },
        yAxis: {
          title: '',
          format: function(val) {
            return val.toFixed(2);
          },
          min: 0
        },
        width: windowWidth,
        height: 200,
        dataLabel: false,
        dataPointShape: true,
        extra: {
          lineStyle: 'curve'
        }
      });
      addchartlist.push(_yuelineChart);
      var chartdate = {};
      if(this.data.quesbarlist.length>i){
        chartdate = this.data.quesbarlist[i];
        this.baseBar(windowWidth,chartdate,i);
      }
    }
    this.setData({"chartlist":addchartlist});
  },


// Base line chart
 baseBar:function(windowWidth,chartData,i){
  var columnChart = new wxCharts({
    canvasId: 'columnCanvas'+i,
    type: 'column',
    animation: true,
    categories: chartData.categories,
    series: [{
        name: chartData.title,
        data: chartData.data,
        format: function (val, name) {
            return val.toFixed(0) + '分';
        }
    }],
    yAxis: {
        format: function (val) {
            return val + '分';
        },
        // title: '得分',
        min: 0
    },
    xAxis: {
        disableGrid: true,
        type: 'calibration',
    },
    extra: {
        // column: {
        //     width: 15
        // }
    },
    width: windowWidth,
    height: 200,
});
},

  touchHandler: function(e) { //当月用电触摸显示
    //todo 确定是那条图的线
    var ind = parseInt(e.target.dataset.id);
    console.log("chart-id："+ind);
    var yuelineChart = this.data.chartlist[ind];
    var data_index = yuelineChart.getCurrentDataIndex(e);
    console.log(yuelineChart);
    var desc = yuelineChart.opts.series[0].desc[data_index];
    var chartinfo = this.data.chartinfo;
    var that = this;
    yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
      background: '#7cb5ec',
      format: function(item, category) {
        console.log(item);
        var tip = category + ' ' + item.name + ':' + item.data ;
        chartinfo[ind] = tip+'\n'+desc;
        that.setData({ chartinfo: chartinfo});
        return tip;
      }
    });
  },
  input_change: function (e) {
    var param = e.detail;
    param['surveyid'] = this.data.id;
    app.api.api_user_find(param).then(res => {
      this.selectComponent("#searchbar").setSelectVals(res);
    })
  },
  
  selected: function (e) {
    this.setData({
      selectuserid: e.detail.wechatuserid,
      papername: e.detail.name,
      answerrecordid: e.detail.answerrecordid
    })
    this.updateData()
  },
  
  drawduiji: function() {
    console.log("draw duiji")
    var that = this
    var res = wx.getSystemInfoSync()
    for (var i = 0; i < that.data.survey.queses.length; i++) {
      var question = that.data.survey.queses[i]
      var context = wx.createContext()
      var totalnumber = 0
      //获取所有人数充满屏幕宽度，以使每个选项有对应的宽度
      for (var j = 0; j < question.optionsForQuesid.length; j++) {
        totalnumber = totalnumber + question.optionsForQuesid[j].answers.length
      }

      var current = 0
      var horizontaloffset = 0;
      //开始绘制每个选项的图形条
      for (var k = 0; k < question.optionsForQuesid.length; k++) {
        var option = question.optionsForQuesid[k]

        horizontaloffset = current / totalnumber * res.windowWidth

        current = current + option.answers.length

        var width = option.answers.length / totalnumber * res.windowWidth
        //防止人数为0的时候没有长度显示
        if (width == 0)
          width = 2;
          
        context.beginPath()
        context.setFillStyle(that.data.color[k % that.data.color.length])
        context.rect(horizontaloffset, 0, width, res.windowWidth * 100 / 750)
        context.fill()
      }
      wx.drawCanvas({
        canvasId: 'Canvasduiji' + parseInt(i + 1),
        actions: context.getActions()
      })

    }
  },

  drawtiaoxing: function() {
    var that = this
    var res = wx.getSystemInfoSync()
    for (var i = 0; i < that.data.survey.queses.length; i++) {

      var question = that.data.survey.queses[i]
      var context = wx.createContext()
      var maxnumber = 0
      //获取最多人数的选项使图形充满屏幕宽度，其他选项根据比例调整长度
      for (var j = 0; j < question.optionsForQuesid.length; j++) {
        if (question.optionsForQuesid[j].answers.length > maxnumber) {
          maxnumber = question.optionsForQuesid[j].answers.length
        }
      }

      //开始绘制每个选项的图形条
      for (var k = 0; k < question.optionsForQuesid.length; k++) {
        var option = question.optionsForQuesid[k]
        var recheight = res.windowWidth * 200 / 750 / question.optionsForQuesid.length
        var vertioffset = k * recheight
        var width = option.answers.length / maxnumber * res.windowWidth
        //防止人数为0的时候没有长度显示
        if (width == 0)
          width = 2;

        context.beginPath()
        context.setFillStyle(that.data.color[k % that.data.color.length])
        context.rect(0, vertioffset, width, recheight)
        context.fill()
      }
      wx.drawCanvas({
        canvasId: 'Canvastiaoxing' + parseInt(i + 1),
        actions: context.getActions()
      })

    }
  }
})